#!/bin/bash
#
# This will generate feed.rss with the content of your posts.
#
#    Copyright 2015 K. Zimmermann - https://notabug.org/kzimmermann
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

# -- Change this if you're using a different database file!
DB="main.db"

# This function checks all recent posts stored in the database:
discover() {
    echo $(sqlite3 $DB "SELECT id FROM articles ORDER BY pubdate DESC")
}

# This function queries the database: 
# $1 is the data you want.
# $2 is the id of the entry (obtained through discover())
fetcher() {
    if [ -z $2 ]
    then 
        echo "Error: no ID provided!"
        exit 1
    else
        case "$1" in
            "title" )
                result=$(sqlite3 $DB "SELECT title FROM articles WHERE id=$2")
                ;;
            "summary" )
                result=$(sqlite3 $DB "SELECT body FROM articles WHERE id=$2" | head -1)
                ;;
            "pubdate" )
                result=$(sqlite3 $DB "SELECT pubdate FROM articles WHERE id=$2")
                ;;
            * )
                result="Error: could not fetch data '$1'"
                ;;
        esac
    fi
    echo -e "$result"
}

post_list=$(discover)

# Quick test to see if fetching the two first lines work.
#for id in $post_list
#do
#    echo -e $(fetcher "summary" $id | head -2)
#done

# time to build the file!
cat <<EOF > feed.rss
<?xml version="1.0" encoding="utf-8"?>
<!-- 
    Generated automatically as a test for kzimmermann's blog.
-->
<rss version="2.0">
    <channel>
        <title>Klaus Zimmermann speaks</title>
        <link>http://kzimmermann.nerdpol.ovh</link>
        <description>
            Klaus Zimmermann's article repository on coding, hacking and the
            experiences on hosting a website in your own room. 
        </description>
        <!-- Publishing begins -->
EOF
for id in $post_list
do
cat <<EOF >> feed.rss
        <item>
            <title>$(fetcher "title" $id)</title>
            <link>http://kzimmermann.nerdpol.ovh?article&amp;id=$id</link>
            <guid>http://kzimmermann.nerdpol.ovh?article&amp;id=$id</guid>
            <pubDate>$(date -d $(fetcher "pubdate" $id ) -u)</pubDate>
            <description>
                $(fetcher "summary" $id)
            </description>
        </item>
EOF
done
cat <<EOF >> feed.rss
    </channel>
</rss>
EOF
